var websocket = require('ws').Server

var online_userlist = [] //在线用户列表

// 解析cookies
var get_cookies = function (request) {
    var cookies = {};
    request.headers && request.headers.cookie.split(';').forEach(function (cookie) {
        var parts = cookie.match(/(.*?)=(.*)$/)
        cookies[parts[1].trim()] = (parts[2] || '').trim();
    });
    return cookies;
};

// 定义消息类型 join leava normal
function typeMsg(type, user, msg) {
    return {
        type: type,
        admin: user || '',
        msg: msg || ''
    }
}



function wsServer() {
    this.wsServer = null
    //初始化服务器
    this.init = function init(server) {
        //挂载到http服务器
        if (server) {
            this.wsServer = new websocket({
                server: server
            })

        } else {
            return
        }
    }


    // 连接模块 
    this.wsConnect = function () {
        console.log('开启websocket连接---------')
        if (this.wsServer) {
            this.wsServer.on('connection', (ws,req) => {
                try{
                    ws.send(JSON.stringify( get_cookies(req) ))
                }catch(err){
                    console.log(err)
                }
                console.log('this.wsServer: ', this.wsServer);
                ws.send(JSON.stringify(typeMsg('join', '目前在线人数', this.wsServer.clients.keys())))
                // msg为一个对象包含发送者与主体
                ws.on('message', msg => {
                    let handleMsg = JSON.parse(msg)
                    this.wsServer.clients.forEach(function each(client) {
                        client.send(JSON.stringify(typeMsg('normal', handleMsg.admin, handleMsg.msg)))
                    })
                })
            })
        } else {
            return
        }

    }


}

var wsConstructor = new wsServer()
module.exports = {
    init: wsConstructor.init,
    wsConnect: wsConstructor.wsConnect
}